<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :limit="1"
      :file-list="fileList"
      :on-preview="handlePreview"
      :class="{
        disabled: fileComputed,
      }"
      :on-remove="handleRemove"
      :http-request="handleUpload"
      :on-change="handleChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="imgUrl" style="width: 100%" alt="">
    </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDQmu0HrSQcZeU3cqA4iCcmgYidIhrQrjy', // 身份识别 ID
  SecretKey: 'jDRPmTx8rrdBTWXINPltwjKvJRmqfEYl' // 身份密钥
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [
        // { url: 'https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF' }
      ],
      showDialog: false,
      imgUrl: ''
    }
  },
  computed: {
    // 设定一个计算属性，判断是否已经上传完了一张
    fileComputed() {
      return this.fileList.length >= 1
    },
    uploadAllSuccess() {
      return this.fileList.every((item) => item.status === 'success')
    }
  },
  methods: {
    handlePreview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid)
    },
    handleUpload(params) {
      if (!params.file) return
      const uid = params.file.uid
      const fileObj = this.fileList.find((item) => item.uid === uid)
      fileObj.status = 'uploading'
      cos.putObject({
        Bucket: 'ifer-1253924894', // 桶名称
        Region: 'ap-nanjing', // 地域
        Key: params.file.name, // 文件名
        Body: params.file, // 要上传的文件对象
        onProgress: (progressData) => {
          fileObj.percentage = parseInt(progressData.percent * 100)
        }
      }, function(err, data) {
        if (err) {
          console.log(err)
          return
        }
        fileObj.url = 'https://' + data.Location
        fileObj.status = 'success'
      })
    },
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      // 文件类型
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      // 检查大小
      // const maxSize = 1 * 1024 * 1024
      // if (maxSize < file.size) {
      //   this.$message.error('图片大小最大不能超过5M')
      //   return false
      // }
      const isSize5M = file.size / 1024 / 1024 > 5
      if (isSize5M) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      return true
    }
  }
}
</script>
<style scoped lang="scss">
  .disabled {
      ::v-deep {
          .el-upload--picture-card {
              display: none;
          }
      }
  }
</style>
